#coding=utf-8

# import sys;
import json;
import random;
import urllib;
import requests;
import time;
import hashlib;

host_server_address_index = 0
host_server_address = ["http://10.6.0.220:2500/nfclock/","http://10.6.0.221:2500/nfclock/","http://10.6.26.130:2507/nfclock/"]

#server_address = "http://10.6.0.220:2500/nfclock/"
server_address = "http://10.6.26.130:2507/nfclock/"
auth_secret = "kCAevYplcaJiEQvYYJsDr6mkWm19kArv"
auth_key = "dwy6fiY2WYorbFoK"



def saveHttpResultToFile(file,str):
    file = open(file, "wb");
    file.write(str);
    file.close();


def md5_encode(arg):
    hash = hashlib.md5()
    hash.update(arg)
    return hash.hexdigest()


def check_retCode(jsonResp):
    text = json.loads(jsonResp)
    retCode = int(text["code"])
    print("retCode=",retCode)
    if retCode == 70505  or  retCode == 70506:
        global host_server_address_index
        global server_address
        host_server_address_index += 1
        if host_server_address_index >= len(host_server_address):
            host_server_address_index = 0
        server_address = host_server_address[host_server_address_index]
        print("Change server address to ",server_address)


def lockHttpTest_queryDeviceParam(sn):
    url = server_address+"queryDeviceParam"
    headers = {'content-type': 'application/json'}

    timestamp = str(int(round(time.time()*1000)))
    tmpParams = {'sn':sn,'timestamp':timestamp}
    tmpStr = ""
    for key in tmpParams.keys():
        tmpStr += tmpParams[key]
    tmpStr += auth_secret
    token = md5_encode(tmpStr.encode('utf-8'))
    params = {'sn':sn,'auth_key':auth_key,'token':token,'timestamp':timestamp}
    payload = {'message': "Opportunities and challenges together"}

    currentTime =  time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    r = requests.get(url, headers = headers,params = params)
    print("url=",r.url)
    print(r.status_code)
    respStr = str(r.content,encoding = "utf-8")
    print(currentTime,respStr)
    check_retCode(respStr)


